require '../db_help/db_help'
require 'iconv'
require 'ruby-debug'

class ExportData

	def initialize
		output_file = "result.log"
		@log = open(output_file, (File::WRONLY | File::APPEND | File::CREAT))
		
		@source_db_config = {"host" => '118.126.2.138', 'encoding' => 'gbk', 'username' => 'root', 'password' => 'admin', 'database' => 'lady_spider'}
		@target_db_config = {"host" => '118.126.2.138', 'encoding' => 'utf8', 'username' => 'root', 'password' => 'admin', 'database' => 'tao_hidoudou'}
		@production_db_config = {"host" => '118.126.2.138', 'encoding' => 'utf8', 'username' => 'root', 'password' => 'admin', 'database' => 'hidoudou_staging'}
		@source_db = DBHelp::DBHelp.create(@source_db_config)
		@target_db = DBHelp::DBHelp.create(@target_db_config)
		@production_db = DBHelp::DBHelp.create(@production_db_config)
	end
	
	def export_items
		sid = 0
		table = "spider_items"
		sql = "select * from #{table} where id > #{sid} order by id asc"
		rets = @source_db.query(sql)

		rets.each_hash do |r|
			sid = r["id"]	
			@log.puts sid
			#puts sid #if cur_cum % 1000 == 0

			h = {}
			begin
				r.each do |k,v|
					h[k] = Iconv.conv('utf-8','gbk', r[k])
				end
				h['table'] = table
				@target_db.query(@target_db.build_sql(h))
				new_item_id = "0"
				@target_db.query("select id from spider_items order by id desc limit 1").each_hash {|r| new_item_id = r["id"]}
				export_item_comments(r['id'], new_item_id)
			rescue
				puts "Error:#{sid}"
			end
			
		end
		@log.close
	end
	
	def export_item_comments(item_id, new_item_id)
		sid = 0
		table = "spider_item_comments"
		sql = "select * from #{table} where spider_item_id = #{item_id} order by id "
		rets = @source_db.query(sql)
		
		rets.each_hash do |r|
			sid = r["id"]				
			h = {}
			begin
				r.each do |k,v|
					h[k] = Iconv.conv('utf-8','gbk', r[k])
				end
				h['spider_item_id'] = new_item_id
				h['table'] = table
				@target_db.query(@target_db.build_sql(h))
			rescue
			end
		end
	end
	
	def export_styles
		export("item_styles")
	end
	
	def export(table)
		sid = 0
		sql = "select * from #{table} where id > #{sid} order by id asc"
		rets = @source_db.query(sql)
		rets.each_hash do |r|
			sid = r["id"]				
			#puts sid
			
			h = {}
			begin
				r.each do |k,v|
					h[k] = Iconv.conv('utf-8','gbk', r[k])
				end
				
				h['table'] = table
				@production_db.query(@production_db.build_sql(h))
				
			rescue
			end
			
		end
	end
end

#ExportData.new().export_items
ExportData.new().export_styles
